import logging
import os
from logging.handlers import RotatingFileHandler
from .config import ConfigHandler

class Logger:
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance.logger = logging.getLogger('singleton_logger')
            if not cls._instance.logger.handlers:
                # 从 ConfigHandler 获取配置
                config_handler = ConfigHandler()
                logging_config = config_handler.get_logging_config()
                log_dir = logging_config['log_dir']
                console_logging = logging_config['console_logging']

                # 创建日志目录
                if not os.path.exists(log_dir):
                    os.makedirs(log_dir)

                formatter = logging.Formatter('%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s')

                # 文件处理器
                max_bytes = logging_config['max_bytes']
                backup_count = logging_config['backup_count']
                file_handler = RotatingFileHandler(os.path.join(log_dir, 'app.log'), maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8')
                file_handler.setFormatter(formatter)
                cls._instance.logger.addHandler(file_handler)

                # 控制台处理器
                if console_logging:
                    console_handler = logging.StreamHandler()
                    console_handler.setFormatter(formatter)
                    console_handler.setLevel(logging.INFO)
                    cls._instance.logger.addHandler(console_handler)

                log_level = logging_config.get('log_level', 'DEBUG')
                log_level_mapping = {
                    'DEBUG': logging.DEBUG,
                    'INFO': logging.INFO,
                    'WARNING': logging.WARNING,
                    'ERROR': logging.ERROR,
                    'CRITICAL': logging.CRITICAL
                }
                cls._instance.logger.setLevel(log_level_mapping.get(log_level, logging.DEBUG))
        return cls._instance

    def get_logger(self):
        return self.logger

logger = Logger().get_logger()